package com.cy.pj.modules.controller;

import com.cy.pj.module.pojo.ResponseResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@RestController
public class JsonController {
    @RequestMapping("/doConvertMapToJson")
    //加了此注解的方法，如果返回值为map或pojo这样的对象，系统底层会将这样的数据转化成JSON格式的字符串，然后响应到客户端
    public Map<String,Object> doConvertMapToJson(){
        Map<String,Object> map=new HashMap<>();
        map.put("state", 1);
        map.put("message", "ok");
        return map;
    }
    @RequestMapping("/doPrintJsonToClient01")
    public String doPrintJsonToClient01() throws JsonProcessingException {
        Map<String,Object> map=new HashMap<>();
        map.put("state", 1);
        map.put("message", "ok");
        //将map手动转化成JSON字符串
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonStr = objectMapper.writeValueAsString(map);
        System.out.println("jsonStr="+jsonStr);
        //将这个json字符串响应到客户端
        return jsonStr;
    }
    @RequestMapping("/doPrintJsonToClient02")
    public void doPrintJsonToClient02(HttpServletResponse response) throws IOException {
        Map<String,Object> map=new HashMap<>();
        map.put("state", 0);
        map.put("message", "Error");
        //将map手动转化成JSON字符串
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonStr = objectMapper.writeValueAsString(map);
        System.out.println("jsonStr="+jsonStr);
        //将这个json字符串响应到客户端
        response.setCharacterEncoding("utf-8");//设置响应数据的编码
        response.setContentType("text/json;charset=utf-8");//告诉客户端响应数据的类型以及编码
        PrintWriter out = response.getWriter();
        out.println(jsonStr);
        out.flush();
    }
    @RequestMapping("/doConvertResponseToJson")
    public ResponseResult doConvertResponseToJson(){
        ResponseResult result=new ResponseResult();
        result.setCode(200);
        result.setMessage("ok");
        return result;
    }
}
